<template>
  <div class="shop-analytics">
    <el-card class="page-header">
      <template #header>
        <div class="header-title">
          <h2>商城数据分析</h2>
          <div class="filter-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              @change="handleDateChange"
            />
            <el-button type="primary" @click="refreshData">刷新数据</el-button>
            <el-button @click="exportData">导出报表</el-button>
          </div>
        </div>
      </template>
    </el-card>

    <!-- 数据概览 -->
    <div class="data-overview">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">¥{{ stats.totalSales }}</div>
              <div class="data-label">总销售额</div>
            </div>
            <div class="data-trend">
              <span class="trend-value" :class="stats.salesTrend > 0 ? 'up' : 'down'">
                {{ stats.salesTrend > 0 ? '+' : '' }}{{ stats.salesTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">{{ stats.totalOrders }}</div>
              <div class="data-label">订单总数</div>
            </div>
            <div class="data-trend">
              <span class="trend-value" :class="stats.ordersTrend > 0 ? 'up' : 'down'">
                {{ stats.ordersTrend > 0 ? '+' : '' }}{{ stats.ordersTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">¥{{ stats.avgOrderValue }}</div>
              <div class="data-label">平均客单价</div>
            </div>
            <div class="data-trend">
              <span class="trend-value" :class="stats.avgOrderValueTrend > 0 ? 'up' : 'down'">
                {{ stats.avgOrderValueTrend > 0 ? '+' : '' }}{{ stats.avgOrderValueTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="data-card">
            <div class="data-card-content">
              <div class="data-value">{{ stats.productsSold }}</div>
              <div class="data-label">售出商品数</div>
            </div>
            <div class="data-trend">
              <span class="trend-value" :class="stats.productsSoldTrend > 0 ? 'up' : 'down'">
                {{ stats.productsSoldTrend > 0 ? '+' : '' }}{{ stats.productsSoldTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表展示 -->
    <div class="chart-container">
      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>销售趋势</span>
                <el-radio-group v-model="salesTrendType" size="small" @change="updateSalesTrend">
                  <el-radio-button label="daily">日</el-radio-button>
                  <el-radio-button label="weekly">周</el-radio-button>
                  <el-radio-button label="monthly">月</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="salesTrendChart" class="chart"></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>商品类别销售占比</span>
              </div>
            </template>
            <div ref="categorySalesChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>热销商品 TOP 10</span>
              </div>
            </template>
            <el-table
              :data="topProducts"
              style="width: 100%"
              max-height="350"
              border
              stripe
            >
              <el-table-column type="index" width="50" align="center" />
              <el-table-column prop="name" label="商品名称" min-width="150" show-overflow-tooltip />
              <el-table-column prop="price" label="单价" width="80">
                <template #default="scope">
                  ¥{{ scope.row.price }}
                </template>
              </el-table-column>
              <el-table-column prop="sold" label="销量" width="80" sortable />
              <el-table-column prop="revenue" label="销售额" width="100">
                <template #default="scope">
                  ¥{{ scope.row.revenue }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>订单状态分布</span>
              </div>
            </template>
            <div ref="orderStatusChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElMessage } from 'element-plus'
// import * as echarts from 'echarts'
// import { getOrderStats } from '@/api/order'

// 图表实例
const salesTrendChart = ref(null)
const categorySalesChart = ref(null)
const orderStatusChart = ref(null)

// 图表DOM元素
const salesTrendChartEl = ref(null)
const categorySalesChartEl = ref(null)
const orderStatusChartEl = ref(null)

// 过滤条件
const dateRange = ref([])
const salesTrendType = ref('daily')

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 数据统计
const stats = reactive({
  totalSales: 158652.35,
  salesTrend: 15.8,
  totalOrders: 1835,
  ordersTrend: 8.5,
  avgOrderValue: 86.46,
  avgOrderValueTrend: 6.7,
  productsSold: 4592,
  productsSoldTrend: 12.3
})

// 热销商品数据
const topProducts = ref([
  { id: 1, name: '专业血压计', price: 299, sold: 256, revenue: 76544 },
  { id: 2, name: '智能体脂秤', price: 199, sold: 215, revenue: 42785 },
  { id: 3, name: '瑜伽垫', price: 88, sold: 198, revenue: 17424 },
  { id: 4, name: '运动手环', price: 249, sold: 156, revenue: 38844 },
  { id: 5, name: '按摩枕', price: 159, sold: 145, revenue: 23055 },
  { id: 6, name: '泡茶杯', price: 59, sold: 135, revenue: 7965 },
  { id: 7, name: '复合蛋白粉', price: 189, sold: 128, revenue: 24192 },
  { id: 8, name: '膳食纤维补充剂', price: 129, sold: 112, revenue: 14448 },
  { id: 9, name: '脉搏血氧仪', price: 239, sold: 98, revenue: 23422 },
  { id: 10, name: '助眠香薰机', price: 139, sold: 92, revenue: 12788 }
])

// 销售趋势数据
const salesTrendData = {
  daily: {
    xData: ['5/1', '5/2', '5/3', '5/4', '5/5', '5/6', '5/7'],
    series: [
      {
        name: '销售额',
        type: 'line',
        data: [5862, 4925, 6258, 8152, 7456, 9521, 10235],
        smooth: true,
        areaStyle: {
          opacity: 0.2
        }
      },
      {
        name: '订单数',
        type: 'bar',
        data: [68, 57, 72, 94, 86, 110, 118],
        yAxisIndex: 1
      }
    ]
  },
  weekly: {
    xData: ['第1周', '第2周', '第3周', '第4周'],
    series: [
      {
        name: '销售额',
        type: 'line',
        data: [32586, 38254, 42150, 45662],
        smooth: true,
        areaStyle: {
          opacity: 0.2
        }
      },
      {
        name: '订单数',
        type: 'bar',
        data: [385, 452, 495, 503],
        yAxisIndex: 1
      }
    ]
  },
  monthly: {
    xData: ['1月', '2月', '3月', '4月', '5月'],
    series: [
      {
        name: '销售额',
        type: 'line',
        data: [120568, 115863, 132456, 145789, 158652],
        smooth: true,
        areaStyle: {
          opacity: 0.2
        }
      },
      {
        name: '订单数',
        type: 'bar',
        data: [1425, 1385, 1562, 1728, 1835],
        yAxisIndex: 1
      }
    ]
  }
}

// 商品类别销售占比数据
const categorySalesData = {
  series: {
    name: '类别销售额',
    data: [
      { value: 42, name: '健康监测' },
      { value: 28, name: '运动健身' },
      { value: 18, name: '保健品' },
      { value: 8, name: '护理用品' },
      { value: 4, name: '其他' }
    ]
  }
}

// 订单状态分布数据
const orderStatusData = {
  series: {
    name: '订单状态',
    data: [
      { value: 68, name: '已完成' },
      { value: 15, name: '已发货' },
      { value: 10, name: '待发货' },
      { value: 5, name: '待付款' },
      { value: 2, name: '已取消' }
    ]
  }
}

// 初始化图表
const initCharts = () => {
  // 由于缺少echarts依赖，这里暂时不初始化图表
  // 实际代码应该类似以下：
  
  // 销售趋势图
  // salesTrendChartEl.value = echarts.init(salesTrendChart.value)
  // updateSalesTrend()
  
  // 商品类别销售占比图
  // categorySalesChartEl.value = echarts.init(categorySalesChart.value)
  // categorySalesChartEl.value.setOption({
  //   tooltip: {
  //     trigger: 'item',
  //     formatter: '{a} <br/>{b}: {c}% ({d}%)'
  //   },
  //   legend: {
  //     orient: 'horizontal',
  //     bottom: 0,
  //     data: categorySalesData.series.data.map(item => item.name)
  //   },
  //   series: [
  //     {
  //       name: categorySalesData.series.name,
  //       type: 'pie',
  //       radius: ['40%', '70%'],
  //       avoidLabelOverlap: false,
  //       label: {
  //         show: false,
  //         position: 'center'
  //       },
  //       emphasis: {
  //         label: {
  //           show: true,
  //           fontSize: '18',
  //           fontWeight: 'bold'
  //         }
  //       },
  //       labelLine: {
  //         show: false
  //       },
  //       data: categorySalesData.series.data
  //     }
  //   ]
  // })
  
  // 订单状态分布图
  // orderStatusChartEl.value = echarts.init(orderStatusChart.value)
  // orderStatusChartEl.value.setOption({
  //   tooltip: {
  //     trigger: 'item',
  //     formatter: '{a} <br/>{b}: {c}% ({d}%)'
  //   },
  //   legend: {
  //     orient: 'horizontal',
  //     bottom: 0,
  //     data: orderStatusData.series.data.map(item => item.name)
  //   },
  //   series: [
  //     {
  //       name: orderStatusData.series.name,
  //       type: 'pie',
  //       radius: ['40%', '70%'],
  //       avoidLabelOverlap: false,
  //       label: {
  //         show: false,
  //         position: 'center'
  //       },
  //       emphasis: {
  //         label: {
  //           show: true,
  //           fontSize: '18',
  //           fontWeight: 'bold'
  //         }
  //       },
  //       labelLine: {
  //         show: false
  //       },
  //       data: orderStatusData.series.data
  //     }
  //   ]
  // })
}

// 更新销售趋势图
const updateSalesTrend = () => {
  // 如果缺少echarts依赖，这里暂时不实现更新图表逻辑
  // 实际代码应该类似以下：
  
  // if (!salesTrendChartEl.value) return
  
  // salesTrendChartEl.value.setOption({
  //   tooltip: {
  //     trigger: 'axis',
  //     axisPointer: {
  //       type: 'cross',
  //       crossStyle: {
  //         color: '#999'
  //       }
  //     }
  //   },
  //   grid: {
  //     left: '3%',
  //     right: '4%',
  //     bottom: '10%',
  //     containLabel: true
  //   },
  //   legend: {
  //     data: ['销售额', '订单数'],
  //     bottom: 0
  //   },
  //   xAxis: [
  //     {
  //       type: 'category',
  //       data: salesTrendData[salesTrendType.value].xData,
  //       axisPointer: {
  //         type: 'shadow'
  //       }
  //     }
  //   ],
  //   yAxis: [
  //     {
  //       type: 'value',
  //       name: '销售额(元)',
  //       min: 0,
  //       splitLine: {
  //         show: true,
  //         lineStyle: {
  //           type: 'dashed'
  //         }
  //       }
  //     },
  //     {
  //       type: 'value',
  //       name: '订单数',
  //       min: 0,
  //       splitLine: {
  //         show: false
  //       }
  //     }
  //   ],
  //   series: salesTrendData[salesTrendType.value].series
  // })
}

// 更新图表
const updateCharts = () => {
  // 更新销售趋势图表
  if (salesTrendChartEl.value) {
    salesTrendChartEl.value.setOption({
      xAxis: { data: salesTrendData[salesTrendType.value].xData },
      series: salesTrendData[salesTrendType.value].series
    })
  }

  // 更新分类销售图表
  if (categorySalesChartEl.value) {
    categorySalesChartEl.value.setOption({
      series: [categorySalesData.series]
    })
  }

  // 更新订单状态图表
  if (orderStatusChartEl.value) {
    orderStatusChartEl.value.setOption({
      series: [orderStatusData.series]
    })
  }
}

// 处理日期变化
const handleDateChange = () => {
  // 处理日期变化逻辑，更新相应数据
  updateCharts()
  ElMessage.success('日期范围已更新')
}

// 刷新数据
const refreshData = () => {
  ElMessage.success('数据已刷新')
  updateCharts()
}

// 导出报表
const exportData = () => {
  ElMessage.success('报表导出中，请稍后查看下载文件')
}

// 监听窗口大小变化，重新调整图表大小
const resizeHandler = () => {
  salesTrendChartEl.value?.resize()
  categorySalesChartEl.value?.resize()
  orderStatusChartEl.value?.resize()
}

// 监听销售趋势类型变化
watch(salesTrendType, () => {
  updateSalesTrend()
  updateCharts()
})

// 生命周期钩子
onMounted(() => {
  // 设置默认日期范围为最近一个月
  dateRange.value = dateShortcuts[1].value()
  
  // 初始化图表
  setTimeout(initCharts, 100)
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', resizeHandler)
})

onBeforeUnmount(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', resizeHandler)
})
</script>

<style scoped>
.shop-analytics {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
}

.filter-actions {
  display: flex;
  gap: 15px;
}

.data-overview {
  margin-bottom: 20px;
}

.data-card {
  height: 120px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.data-card-content {
  text-align: center;
}

.data-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.data-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.data-trend {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.trend-value {
  font-weight: 500;
}

.trend-value.up {
  color: #67c23a;
}

.trend-value.down {
  color: #f56c6c;
}

.trend-label {
  color: #909399;
}

.chart-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 350px;
}

@media (max-width: 768px) {
  .header-title {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-actions {
    margin-top: 15px;
    flex-wrap: wrap;
  }
  
  .chart {
    height: 250px;
  }
}
</style>